package com.gonsin.license;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

public class QuartzUtil {

    private static final SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();

    /**添加一个延迟性定时任务
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass  任务
     * @param time  任务执行时间 (13位 Long)
     * @param param  任务所需参数
     */
    public static void addDelayJob(String jobName,String jobGroupName,
                                   String triggerName,String triggerGroupName,
                                   Class<? extends Job> jobClass,Long time,
                                   JobDataMap param) {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            JobDetail jobDetail= JobBuilder
                    .newJob(jobClass)
                    .withIdentity(jobName,jobGroupName)
                    .usingJobData(param)
                    .build();
            Trigger trigger = TriggerBuilder   // 触发器
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .startAt(new Date(time))
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**添加一个延迟性定时任务
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass  任务
     * @param time  任务执行时间(10位 Integer)
     * @param param  任务所需参数
     */
    public static void addDelayJob(String jobName,String jobGroupName,
                                   String triggerName,String triggerGroupName,
                                   Class<? extends Job> jobClass,Integer time,
                                   JobDataMap param) {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            JobDetail jobDetail= JobBuilder
                    .newJob(jobClass)
                    .withIdentity(jobName,jobGroupName)
                    .usingJobData(param)
                    .build();
            Trigger trigger = TriggerBuilder   // 触发器
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .startAt(new Date(time * 1000L))
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**添加一个周期性定时任务
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass  任务
     * @param IntervalSeconds  间隔时间(秒)
     * @param param 参数
     */
    public static void addIntervalJob(String jobName, String jobGroupName,
                                      String triggerName, String triggerGroupName,
                                      Class<? extends Job> jobClass,Integer IntervalSeconds,
                                      JobDataMap param) {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();
            SimpleTrigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(IntervalSeconds))
                    .usingJobData(param)
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**添加一个周期性定时任务
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass  任务
     * @param time  时间设置，参考quartz说明文档
     */
    public static void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class<? extends Job> jobClass,
                              String time) {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任务名，任务组，任务执行类
            CronTrigger trigger = TriggerBuilder   // 触发器
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**添加一个周期性定时任务  （带参数）
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass  任务
     * @param time  时间设置，参考quartz说明文档
     */
    public static void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class<? extends Job> jobClass,
                              String time,JobDataMap jobDataMap) {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任务名，任务组，任务执行类
            CronTrigger trigger = TriggerBuilder   // 触发器
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .usingJobData(jobDataMap)
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();        // 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**修改一个任务的触发时间
     * @param triggerName   任务名称
     * @param triggerGroupName  传过来的任务名称
     * @param time  更新后的时间规则
     */
    public static void modifyJobTime(String triggerName, String triggerGroupName, String time) {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();                             //通过SchedulerFactory构建Scheduler对象
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);    //通过触发器名和组名获取TriggerKey
            CronTrigger trigger = (CronTrigger)scheduler.getTrigger(triggerKey);                //通过TriggerKey获取CronTrigger
            if (trigger == null)  return;
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(trigger.getCronExpression());
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                trigger = trigger.getTriggerBuilder()      //重新构建trigger
                        .withIdentity(triggerKey)
                        .withSchedule(scheduleBuilder)
                        .withSchedule(CronScheduleBuilder.cronSchedule(time))
                        .build();
                scheduler.rescheduleJob(triggerKey, trigger);               //按新的trigger重新设置job执行
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**移除一个任务
     * @param jobName   任务名
     * @param jobGroupName  任务组名
     * @param triggerName   触发器名
     * @param triggerGroupName  触发器组名
     */
    public static void removeJob(String jobName, String jobGroupName,String triggerName, String triggerGroupName) {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);    //通过触发器名和组名获取TriggerKey
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);                           //通过任务名和组名获取JobKey
            scheduler.pauseTrigger(triggerKey); // 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(jobKey);        // 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 启动所有定时任务
     */
    public static void startJobs() {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭所有定时任务
     */
    public static void shutdownJobs() {
        try {
            Scheduler scheduler = gSchedulerFactory.getScheduler();
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
